// 接口返回值code说明
// 200=>正常；
// 400=>报错；
// 401=>需要登陆；
// 50001=>没有购买权限，错误并且弹出报错，报错内容为 error(小程序跳转到个人中心认证车手页面)；

var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly; //创建fly实例
var tokenFly = new Fly();
import util from './index.js';
import siteInfo from '../siteinfo.js';
import $store from "@/store/index.js"

// 打印站点信息siteInfo
let allSiteInfo = Object.assign({}, {
	time: "2022年09月129日 19:50",
	remark: "(test)~ update:apple_login~",
}, siteInfo)
console.log(allSiteInfo);

import {
	networkError,
	serverError,
	msgError,
	authError,
	vipError
} from './error.js';
//添加finally方法,用于指定不管 Promise 对象最后状态如何，都会执行的操作
Promise.prototype.finally = function(callback) {
	let P = this.constructor;
	return this.then(
		value => P.resolve(callback()).then(() => value),
		reason => P.resolve(callback()).then(() => {
			throw reason
		})
	);
};
const isW7 = false
const formatUrl = function(url) {
	let model_name = "farm";
	let baseUrl = isW7 ?
		`${siteInfo.siteroot}?i=${siteInfo.uniacid}&t=${siteInfo.multiid}&v=${siteInfo.version}&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=${model_name}&s=${url}` :
		`${siteInfo.siteroot}?i=${siteInfo.uniacid}&m=${model_name}&s=${url}`
	return baseUrl;
}
//阿里云地址转为本地域名的 
const formatImageUrl = function(url) {
	return url.includes(siteInfo.siteroot) ? url :
		`${formatUrl("card/getImage")}&path=${encodeURIComponent(url)}`
}

//微信小程序登录
const wxLogin = async function() {
	let {
		query
	} = await uni.getLaunchOptionsSync();
	console.log('query', query)
	let url = formatUrl("index/login")
	try {
		uni.showLoading({
			title: "登录中..."
		})
		let [providerErr, providerData] = await uni.getProvider({
			service: 'oauth',
		});
		let [loginErr, loginData] = await uni.login({
			provider: providerData.provider[0]
		});

		let login_param = {
			code: loginData.code,
			pid: query.pid
		}

		console.log("login_param==>", login_param);

		let d = await tokenFly.post(url, login_param);
		let {
			code,
			data,
			error
		} = d.data

		if (code !== 200) {
			uni.hideLoading()
			serverError({
				code,
				msg: error
			});
			throw d;
		}
		//登录成功
		uni.hideLoading()
		$store.commit('updateUserItem', {
			key: 'autograph',
			val: data.autograph
		})
		$store.commit('updateUserItem', {
			key: 'userInfo',
			val: data.data
		})
		return data;
	} catch (e) {
		uni.hideLoading()
		let {
			code,
			error
		} = e.response.data
		if (code !== 200) {
			serverError({
				code,
				msg: error
			});
		}
		return await Promise.reject(e);
	}
}
//设置超时
fly.config.timeout = 15000;

//设置请求基地址

//给所有请求添加自定义header
fly.config.headers = tokenFly.config.headers = {
	"content-type": "application/json"
}

//添加请求拦截器
fly.interceptors.request.use(
	async (request) => {
		//添加验证token
		request.headers['autograph'] = $store.state.user.autograph || '';
		// #ifdef APP-PLUS
		request.headers['isapp'] = 1;
		// #endif
		// #ifdef H5
		request.headers['isapp'] = 2;
		// #endif
		return request;
	})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
	async (response) => {
			//token过期验证
			if (response.data.code != 401) return response;
			fly.lock()

			//#ifdef  MP-WEIXIN
			console.log("==> MP-WEIXIN 401")
			await wxLogin();
			//#endif

			response.request.headers["autograph"] = $store.state.user.autograph || ''
			fly.unlock();
			return fly.request(response.request);
		},
		async (err) => {
			console.log(err, "=======fly.interceptors.response.use err");
			let {
				status = 0,
			} = err

			util.hideAll()
			networkError({
				code: status,
			})
			//网络错误
			return await Promise.reject(err);
		}
)

//统一处理请求,satus=200网络正常code=200服务器正常
const httpType = ["post", "get"]
const formatReq = function() {
	let req = {};
	httpType.forEach((type) => {
		req[type] = async function(url, param) {
			//构造请求地址
			url = formatUrl(url);
			let res = await fly[type](url, param)
			// console.log("=========res=======",res)
			// #ifdef MP-BAIDU
			res.data = typeof(res.data) == "string" ? JSON.parse(res.data) : res.data;
			// #endif
			let {
				code,
				error,
				data
			} = res.data
			code = code * 1
			if (code === 200) return data;
			//code!=200抛出错误
			util.hideAll();
			if (code == 50001) {
				authError({
					msg: error
				})
			} else if (code == -407) {
				let url = `/shop/pages/choose-store`
				util.goUrl({
					url
				})
			} else if (code == 50002) {
				vipError({
					msg: error
				})
			} else if (code == 400 && error) {
				console.log(code, error, "code != 200");
				msgError({
					msg: error
				})
			}
			return await Promise.reject(res.data);
		}
	})
	return req;
}
const req = formatReq();


// 定义上传,picture--代表图片 audio--音频 video--视频,默认picture
const uploadFile = async (url, {
	name = "file",
	filePath,
	header = {
		autograph: $store.state.user.autograph || '',
		// #ifdef APP-PLUS
		isapp: 1,
		// #endif
		// #ifdef H5
		isapp: 2,
		// #endif
	},
	formData = {
		type: "picture",
	}
} = {}) => {
	url = formatUrl(url);
	let [, res] = await uni.uploadFile({
		url,
		filePath,
		name,
		formData,
		header,
	})

	if (res.statusCode != 200) {
		util.hideAll()
		networkError();
		return await Promise.reject(res);
	}
	let parseData = JSON.parse(res.data)
	//服务器错误
	let {
		code,
		msg,
		data
	} = parseData;
	if (code != 200) {
		util.hideAll()
		serverError({
			code,
			msg
		});
		return await Promise.reject(res);
	}
	return data
}


export {
	fly,
	req,
	uploadFile,
	formatImageUrl,
	formatUrl,
}
